package com.example.designpatterns.iterator.concrete;

import com.example.designpatterns.iterator.Iterator;

/**
 * 类别迭代器 - 特殊迭代器
 * 只遍历指定类别的图书
 */
public class CategoryIterator implements Iterator<Book> {
    private BookCollection bookCollection;
    private String category;
    private int currentIndex;
    
    /**
     * 创建按类别筛选的图书迭代器
     * @param bookCollection 图书集合
     * @param category 需要筛选的类别
     */
    public CategoryIterator(BookCollection bookCollection, String category) {
        this.bookCollection = bookCollection;
        this.category = category;
        this.currentIndex = 0;
    }
    
    @Override
    public boolean hasNext() {
        // 查找下一个符合类别的图书
        int tempIndex = currentIndex;
        while (tempIndex < bookCollection.getLength()) {
            Book book = bookCollection.getBookAt(tempIndex);
            if (book != null && category.equals(book.getCategory())) {
                return true;
            }
            tempIndex++;
        }
        return false;
    }
    
    @Override
    public Book next() {
        if (!hasNext()) {
            return null;
        }
        
        // 找到下一个符合类别的图书
        while (currentIndex < bookCollection.getLength()) {
            Book book = bookCollection.getBookAt(currentIndex);
            currentIndex++;
            
            if (book != null && category.equals(book.getCategory())) {
                return book;
            }
        }
        
        return null;
    }
} 